﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.Cache;

/// <summary>
/// 商家信息
/// </summary>
public partial class Admin_Shop_ShopDetail : AdminPageBase
{
    protected string hasDiscount = "0";

    protected int togo_id
    {
        set
        {
            ViewState["togo_id"] = value;
        }
        get
        {
            return ViewState["togo_id"] == null ? 0 : Convert.ToInt32(ViewState["togo_id"]);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ValidatorSet validator = new ValidatorSet("Admin");
        validator.SetValidator();
        if (!IsPostBack)
        {
            WebUtility.SetDDLCity(DDLArea);


            //编辑
            int TogoId = HjNetHelper.GetQueryInt("id", 0);

            if (TogoId > 0)
            {
                BindTogoData(TogoId);
                hidDataId.Value = TogoId.ToString();
                hidTogoId.Value = TogoId.ToString();
                pageType.InnerHtml = "<span>更新商家信息</span>";
                lbmsg.HRef = "feerule.aspx?tid=" + TogoId;
                lbmsg.Target = "_blank";
                deliverfeelink.HRef = "deliverfeerule.aspx?tid=" + TogoId;
                deliverfeelink.Target = "_blank";

               



            }
            else
            {
                pageType.InnerHtml = "<span>新增商家</span>";
                hidDataId.Value = "0";
                cbIsdelete.Checked = false;
                ddlStatus.SelectedValue = "1";
                hfintime.Value = DateTime.Now.ToShortDateString();
                diagram_tab.Style["display"] = "none";

                lbmsg.HRef = "javascript:";
                lbmsg.InnerText = "请先添加商家，再设置计费规则";
                ddlDeliverGroup.Style["display"] = "none";


                lbmsg.InnerText = "编辑商家时再设置规则";
                deliverfeelink.InnerText = "编辑商家时再设置规则";



                rblPosAttch.Items[0].Selected = true;
                rblPosSrvAd.Items[0].Selected = true;

            }
        }
    }

    Points togoBll = new Points();


    /// <summary>
    /// 获取商家的信息
    /// </summary>
    /// <param name="TogoId"></param>
    protected void BindTogoData(int TogoId)
    {
        PointsInfo info = new PointsInfo();

        info = togoBll.GetModel(TogoId);


        WebUtility.BindList("id", "classname", SectionProxyData.GetSortList().Where(a => a.Status == info.cityid).ToList(), cblqq);
        WebUtility.BindList("IID", "togoname", CacheHelper.GetShopPicTag().Where(a => a.ShopId == info.cityid).ToList(), cbopentime);


        tbName204234.Text = info.Name;
        tbCommPerson.Text = info.CommPerson;
        tbAddress.Text = info.Address;
        tbComm.Text = info.Comm;

        TextBoxtime.Text = info.Opentimes1.ToString("HH:mm");
        TtimeEnd.Text = info.Opentimes2.ToString("HH:mm");

        TextBoxtime2.Text = info.Closetimes1.ToString("HH:mm");
        TtimeEnd2.Text = info.Closetimes2.ToString("HH:mm");

        tbSortNum.Text = info.SortNum.ToString();
        tbIntroduce.Value = info.Introduce;
        hidInTime.Value = info.InTime.ToString();
        ImgUrl1.Value = info.Picture;
        if (!string.IsNullOrEmpty(info.Picture))
        {
            ImgUrl.Src = WebUtility.ShowPic(info.Picture);
        }
        ////登入帐号
        tbLoginName.Text = info.LoginName;
        hidPassword.Value = info.Password;
        hidIsDelete.Value = info.IsDelete.ToString();
        ddlStatus.SelectedValue = info.Status.ToString();//1 正常营业 0 暂停营业 －1 休息中
        cbIsdelete.Checked = info.IsDelete == 1 ? true : false;
        togo_id = TogoId;
        tbPoint.Text = info.point.ToString();
        tbPoint2.Text = info.point.ToString();

        tbSentTime.Text = info.senttime.ToString();

        WebUtility.SelectValue(ddlSentOrg, info.sentorg.Trim());

        tbViewTimes.Text = info.ViewTimes.ToString();
        tbSendFee1.Text = info.SendFee.ToString();
        tbSendFee2.Text = info.SendFee.ToString();

        tbNamePy.Text = info.NamePy;
        tbInve1.Text = info.Inve1.ToString();
        tbemail.Text = info.email;

        WebUtility.SelectValue(DDLArea, info.cityid.ToString());
        WebUtility.SelectValue(ddlPType, info.PType.ToString());
        WebUtility.SelectValue(ddlSN1, info.SN1.Trim());
        WebUtility.SelectValue(ddlSn2Key, info.Sn2Key.Trim());

        WebUtility.BindList("id", "classname", SectionProxyData.GetEdelivergroupList().Where(a => a.Status == info.cityid).ToList(), ddlDeliverGroup);
        WebUtility.SelectValue(ddlDeliverGroup, info.IsCallCenter);

        WebUtility.BindList("id", "RealName", SectionProxyData.GetMarketAdminList().Where(a => a.CityID == info.cityid).ToList(), ddlPHead);
        WebUtility.SelectValue(ddlPHead, info.PEnd);
        // tbPHead.Text = info.PHead;
        tbSendLimit.Text = info.SendLimit.ToString();
        tbspecial.Text = info.special.ToString();

        WebUtility.SelectValue(ddlshowpicture, info.showpicture.ToString());
        WebUtility.CheckValueS(cblqq, info.category);
        WebUtility.CheckValueS(cbopentime, info.OpenTime);
        WebUtility.SelectValue(ddlid, info.ID);
        tbRcvType.Text = info.RcvType.ToString();

        ETogoLocal bll = new ETogoLocal();
        ETogoLocalInfo location = bll.GetInfoById(info.Unid.ToString());
        //如无坐标点则默认
        if (info != null && info.Lat != null && info.Lng != null && info.Lat != "" && info.Lng != "")
        {
            hidLat.Text = info.Lat;
            this.hidLng.Text = info.Lng;
        }
        else
        {
            hidLat.Text ="0";
            this.hidLng.Text = "0";
            mapbox.Style["display"] = "none";
        }

        if (info.MgrCell.Length == 0)
        {
            info.MgrCell = "0";
        }
        

        tbMgrCell.Text = info.MgrCell.ToString();

        WebUtility.SelectValue(ddlPTimes, info.PTimes.ToString());

        WebUtility.SelectValue(ddlEBuilding, info.EBuilding.ToString());
        tbSN2.Text = info.SN2.ToString();
        tbSN22.Text = info.SN2.ToString();


        tboutnitice.Text = info.outnitice.ToString();
        if (info.outnitice.ToString().Length == 0)
        {
            tboutnitice.Text = "0";
        }


        tbmtbindurl.Text = "https://open-erp.meituan.com/storemap?developerId="+  Hangjing.Common.Constant.mt_developerId +"&businessId=2&ePoiId="+info.Unid+"&signKey="+Constant.mt_SignKey+ "&ePoiName=aa&netStore=1";

        meituanbindlogInfo bindlog = new meituanbindlog().GetList(1, 1, "ePoiId='" + info.Unid + "' and mtype=1", "mid", 1).FirstOrDefault();
        if (bindlog != null)
        {
            tbmtunbindurl.Text = "https://open-erp.meituan.com/releasebinding?signKey=" + Constant.mt_SignKey + "&businessId=2&appAuthToken="+bindlog.appAuthToken;
        }



        tbelebindurl.Text = new Hangjing.EleAPIV2.ELEAuth(Context).GetAuthURL(info.Unid);
        if (info.PosAttch == "")
        {
            info.PosAttch = "0";
        }
        if (info.PosSrvAd == "")
        {
            info.PosSrvAd = "0";
        }

        WebUtility.SelectValue(rblPosAttch, info.PosAttch.ToString());
        WebUtility.SelectValue(rblPosSrvAd, info.PosSrvAd.ToString());
        tbMoney.Text = info.money + "";
    }

    /// <summary>
    /// 保存商家的信息 TODO:保存的标志建筑物那块功能是否可以变得更方便强大（删除建筑物）
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btSave_Click1(object sender, EventArgs e)
    {
        int id = HjNetHelper.GetQueryInt("id", 0);
        PointsInfo info = togoBll.GetModel(id);
        if (info == null)
        {
            info = new PointsInfo();
            info.Grade = 0;
            info.money = 0;
            info.Star = 1;
        }
        info.Unid = HjNetHelper.GetQueryInt("id", 0);
        info.ID = ddlid.SelectedValue;
        info.Name = WebUtility.InputText(tbName204234.Text);
        info.Comm = WebUtility.InputText(tbComm.Text);
        info.PType = WebUtility.InputText(ddlPType.SelectedValue, true);
        info.RcvType = WebUtility.InputText(tbRcvType.Text, true);
        info.NamePy = WebUtility.InputText(tbNamePy.Text);
        info.CommPerson = WebUtility.InputText(tbCommPerson.Text);
        info.SendLimit = Convert.ToDecimal(tbSendLimit.Text);
        info.LoginName = WebUtility.InputText(tbLoginName.Text);

        info.SN1 = ddlSN1.SelectedValue.Trim();
        info.point = 0;
        if (info.SN1 == "0")
        {
            info.point = Convert.ToInt32(WebUtility.InputText(tbPoint.Text));
        }
        else
        {
            info.point = Convert.ToInt32(WebUtility.InputText(tbPoint2.Text));
        }


        info.Sn2Key = ddlSn2Key.SelectedValue;
        info.SendFee = 0;
        if (info.Sn2Key == "0")
        {
            info.SendFee = WebUtility.InputText(tbSendFee1.Text, 'c');
        }
        else
        {
            info.SendFee = WebUtility.InputText(tbSendFee2.Text, 'c');
        }

        info.EBuilding = ddlEBuilding.SelectedValue;
        info.SN2 = "0";

        switch (info.EBuilding)
        {
            case "0":
                info.SN2 = WebUtility.InputText(tbSN2.Text);
                break;
            case "1":
                info.SN2 = WebUtility.InputText(tbSN22.Text);
                break;
        }

        info.PTimes = Convert.ToInt32(ddlPTimes.SelectedValue);
        info.MgrCell = WebUtility.InputText(tbMgrCell.Text);
        info.PHead = WebUtility.InputText(ddlPHead.SelectedItem.Text);
        info.PEnd = ddlPHead.SelectedValue.Length == 0 ? "0" : ddlPHead.SelectedValue;
        info.IsCallCenter = Convert.ToInt32(ddlDeliverGroup.SelectedValue);
        info.Address = WebUtility.InputText(tbAddress.Text);
        info.Introduce = tbIntroduce.Value;
        info.Status = Convert.ToInt32(ddlStatus.SelectedValue);
       
        info.OpenTime = WebUtility.GetcheckStrFix(cbopentime);
        info.Time1Start = DateTime.Now;
        info.Time1End = DateTime.Now;
        info.Time2Start = DateTime.Now;
        info.Time2End = DateTime.Now;
        info.bisnessStart = DateTime.Now;
        info.bisnessend = DateTime.Now;
        info.bisnessStart2 = DateTime.Now;
        info.bisnessend2 = DateTime.Now;
        info.IsDelete = cbIsdelete.Checked ? 1 : 0;
        info.SortNum = Convert.ToInt32(WebUtility.InputText(tbSortNum.Text));
        

        info.category = WebUtility.GetcheckStrFix(cblqq);
        info.senttime = Convert.ToInt32(tbSentTime.Text);
        info.sentorg = WebUtility.InputText(ddlSentOrg.SelectedValue);
        info.special = WebUtility.InputText(tbspecial.Text);

        info.Inve1 = Convert.ToInt32(tbInve1.Text);
        info.cityid = Convert.ToInt32(this.DDLArea.SelectedValue);
        info.Picture = ImgUrl1.Value;
        info.showpicture = Convert.ToInt32(ddlshowpicture.SelectedValue);
        info.foodupdatetime = DateTime.Now;

        info.ViewTimes = Convert.ToInt32(tbViewTimes.Text);
        //营业时间
        info.Opentimes1 = TextBoxtime.Text == "" ? DateTime.Now : Convert.ToDateTime(TextBoxtime.Text);
        info.Opentimes2 = TtimeEnd.Text == "" ? DateTime.Now : Convert.ToDateTime(TtimeEnd.Text);
        info.Closetimes1 = TextBoxtime2.Text == "" ? DateTime.Now : Convert.ToDateTime(TextBoxtime2.Text);
        info.Closetimes2 = TtimeEnd2.Text == "" ? DateTime.Now : Convert.ToDateTime(TtimeEnd2.Text);


        if (info.Closetimes1 < info.Opentimes1)
        {
            AlertScript.RegScript(this.Page, UpdatePanel1, "alert('营业时间段一必须早于营业时间段二');init();");
            return;
        }


        info.StopAM = DateTime.Now;
        info.StopPM = DateTime.Now;
        info.email = WebUtility.InputText(tbemail.Text);
        info.outnitice = WebUtility.InputText(tboutnitice.Text);
        info.BigPicture = "";

        info.PosAttch = rblPosAttch.SelectedValue;
        info.PosSrvAd = rblPosSrvAd.SelectedValue;


        //新增
        if (hidDataId.Value == "0")
        {
            string sqls = "LoginName='" + info.LoginName + "'";
            if (togoBll.GetCount(sqls) > 0)
            {
                AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('新增商家信息失败','text:新增商家信息失败，登录名已存在!','250','150','true','3000','true','text');init();");
                return;
            }


            //判断权限
            int _rs = WebUtility.checkOperator(2);
            if (_rs == 0)
            {
                AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
                return;
            }
            info.InTime = DateTime.Now;
            info.reviewtimes = 0;
            info.PosAddr = "";
            info.PosRoom = "";
           
            info.FlavorGrade = 1;
            info.ServiceGrade = 1;
            info.SpeedGrade = 1;
            info.InTime = DateTime.Now;
            info.ViewTimes = 0;
            info.pop = 0;
            info.Password = WebUtility.GetMd5(tbPassword.Text);
            info.InUse = "Y";
            int togo_num = togoBll.Add(info);

            if (togo_num > 0)
            {
                hidDataId.Value = togo_num.ToString();

                ETogoLocal bll = new ETogoLocal();
                ETogoLocalInfo location = new ETogoLocalInfo();
                location.Lat = WebUtility.InputText(hidLat.Text);
                location.Lng = WebUtility.InputText(hidLng.Text);
                location.TogoId = togo_num;
                location.Polygon = "";
                location.Radius = 0;

                bll.Add(location);
                EasyEatCache.GetCacheService().RemoveObject("/ShopLocallist");


                AlertScript.RegScript(this.Page, UpdatePanel1, "alert('新增商家成功,点击编辑商家,选择区域,市场专员','id:divShowContent','640','150','true','','true','text');gourl('ShopDetail.aspx?id=" + togo_num + "');");
            }
            else
            {
                AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('新增商家失败','text:新增商家失败','250','150','true','','true','text');init();");
            }
        }
        else
        {
            string sqls = "LoginName='" + info.LoginName + "' and unid <> " + info.Unid;
            if (togoBll.GetCount(sqls) > 0)
            {
                AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新商家信息失败','text:更新商家信息失败，登录名已存在!','250','150','true','3000','true','text');init();");
                return;
            }


            //判断权限
            int _rs = WebUtility.checkOperator(3);
            if (_rs == 0)
            {
                AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
                return;
            }
            if (tbPassword.Text != "")
            {
                info.Password = WebUtility.GetMd5(tbPassword.Text);
            }
            if (togoBll.Update(info) > 0)
            {
                AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('您可以继续进行的操作','id:divShowContent','640','150','true','','true','text');init();");
            }
            else
            {
                AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新商家信息失败','text:更新商家信息失败','250','150','true','','true','text');init();");
            }
        }
        Hangjing.Cache.EasyEatCache.GetCacheService().RemoveObject("/shop/shop" + HjNetHelper.GetQueryInt("id", 0) + "/info");

    }

}
